package com.zat.mes.andrmes.dofun.work

import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.AdapterView
import androidx.appcompat.widget.ListPopupWindow
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.listener.OnLoadMoreListener
import com.google.gson.Gson
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.customerview.BottomSignDailog
import com.zat.mes.andrmes.data.Itemm
import com.zat.mes.andrmes.data.LoginResultBean
import com.zat.mes.andrmes.data.ParantTypeItem
import com.zat.mes.andrmes.data.YarnItem
import com.zat.mes.andrmes.dofun.qualitytest.vm.QcPlanViewModel
import com.zat.mes.andrmes.dofun.work.adapter.DayWorkScanProcAdapter
import com.zat.mes.andrmes.dofun.work.adapter.SelectScheduAdapter
import com.zat.mes.andrmes.dofun.work.adapter.YarnInListAdapter
import com.zat.mes.andrmes.dofun.work.vm.YarnInModel
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.utils.DateUtil
import com.zat.mes.andrmes.utils.PreferencesUtil
import com.zat.mes.andrmes.utils.showToast
import kotlinx.android.synthetic.main.activity_deal_on_site.*
import kotlinx.android.synthetic.main.activity_select_schedu.*
import kotlinx.android.synthetic.main.activity_work_scan.*
import kotlinx.android.synthetic.main.activity_yarn_in.*
import kotlinx.android.synthetic.main.layout_title.*
import org.json.JSONObject
import java.util.*
import kotlin.math.log

/**
 * 领纱
 */
class YarnInActivity : BaseActivity() {


    var yarnInModel: YarnInModel? = null
    var qcModel:QcPlanViewModel?=null
    var units: MutableList<ParantTypeItem>? = null
    var schedu:Itemm?=null
    var currentPage: Int = 1
    var yarnInListAdapter: YarnInListAdapter?=null
    override fun init() {
        initView()
        initData()
    }

    private fun initData() {
        val loginResultBean = Gson().fromJson(
            PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
            LoginResultBean::class.java
        )
        var empId = loginResultBean.empid
        var empName = loginResultBean.empname

        yarnInModel = ViewModelProvider(this).get(YarnInModel::class.java)
        yarnInModel?.getYarnInData()?.observe(this, Observer {
            closeLoading()
            showToast(it)
            finish()
        })
        qcModel = ViewModelProvider(this).get(QcPlanViewModel::class.java)
        qcModel?.getParantTypeData()?.observe(this, Observer {
            closeLoading()
            units = it.get("BASIC_YARN_UNIT")
        })
        qcModel?.loadParantTypeList("BASIC_YARN_UNIT")
        showLoading()
       btnYarnIn.setOnClickListener {
           if (TextUtils.isEmpty(tvScheduNo.text)||tvScheduNo.text.length<=4){
               showToast("请选择排班号")
               return@setOnClickListener
           }
           if (TextUtils.isEmpty(etYuanliao.text.toString())){
               showToast("请输入原料名")
               return@setOnClickListener
           }

           val jsonObject = JSONObject()
           jsonObject.put("rawMaterialName", etYuanliao.text.toString())
           var oneUnit = tvUnitOne.getTag(tvUnitOne.id)as ParantTypeItem
           jsonObject.put("unitOneId", oneUnit.typecode)
           jsonObject.put("unitOneName", oneUnit.typename)
           jsonObject.put("unitOnSize",etUnitOneSize.text.toString())

           var twoUnit = tvUnitTwo.getTag(tvUnitTwo.id)as ParantTypeItem
           jsonObject.put("unitTwoId", twoUnit.typecode)
           jsonObject.put("unitTwoName", twoUnit.typename)
           jsonObject.put("unitTwoSize",etUnitTwoSize.text.toString())

           jsonObject.put("yarnEmpId", empId)
           jsonObject.put("yarnEmpName", empName)
           jsonObject.put("factoryId", loginResultBean.factoryid)
           jsonObject.put("workShopId", loginResultBean.workShopid)
           jsonObject.put("classId",loginResultBean.classid)
           jsonObject.put("yarnDate", DateUtil.formatDate(Date()))
           jsonObject.put("scheduId", schedu?.scheduId)
           jsonObject.put("scheduNo", schedu?.schedNo)

           yarnInModel?.postYarnIn(jsonObject.toString())
           showLoading()

       }

        llBtnUnitOne.setOnClickListener {
           showBottomDialog(true,units)
        }
        llBtnUnitTwo.setOnClickListener {
            showBottomDialog(false,units)
        }

        recyclerYarnIn.layoutManager = LinearLayoutManager(baseContext)
        yarnInListAdapter = YarnInListAdapter(R.layout.item_yarn_list)
        recyclerYarnIn.adapter = yarnInListAdapter
        val loadMoreModule = yarnInListAdapter?.loadMoreModule
        // 当数据不满一页时，是否继续自动加载（默认为true）
        loadMoreModule?.isEnableLoadMoreIfNotFullPage = false
        loadMoreModule?.isAutoLoadMore = false
        loadMoreModule?.setOnLoadMoreListener(OnLoadMoreListener {
            requestData(empId.toString())
        })

        yarnInModel?.getYarnInList()?.observe(this, Observer {
            if (it != null) {
                val result = it.result
                if (result != null) {
                    if (result.items != null) {
                        if (currentPage == 1) {
                            if (result.items == null || result.items.size <= 0) {
                                setEmptyVisible()
                            } else {
                                setEmptyGone()
                            }
                            yarnInListAdapter?.setNewData(result.items  as MutableList<YarnItem>)
                        } else {
                            yarnInListAdapter?.addData(result.items)
                        }
                    }
                    if (result.currentPage == result.totalPage) {
                        loadMoreModule?.loadMoreEnd()
                    } else {
                        loadMoreModule?.loadMoreComplete()
                        currentPage++
                    }
                } else {
                    loadMoreModule?.loadMoreEnd()
                }
            } else {
                loadMoreModule?.loadMoreEnd()
            }
        })
        requestData(empId.toString())
    }
    private fun requestData(empId: String?) {
        yarnInModel?.getYarnInList(currentPage,10,empId)

    }

    /**
     * 显示底部弹框 处理方式
     */
    fun showBottomDialog(one:Boolean,list: MutableList<ParantTypeItem>?) {
        BottomSignDailog(this, list, object : BottomSignDailog.OnBottomSelectListener {
            override fun onBottomSelect(parantTypeItem: ParantTypeItem) {
                if (one) {
                    tvUnitOne.text = parantTypeItem.typename
                    tvUnitOne.setTag(tvUnitOne.id,parantTypeItem)
                }else{
                    tvUnitTwo.text = parantTypeItem.typename
                    tvUnitTwo.setTag(tvUnitTwo.id,parantTypeItem)
                }

            }

        })
    }


    private fun initView() {
        setContentView(R.layout.activity_yarn_in)
        tVtitle.text = "领纱"
        rlReturnTitle.visibility = View.VISIBLE
        rlReturnTitle.setOnClickListener { finish() }
        llBtnScheduNo.setOnClickListener { startActivityForResult(Intent(this,SelectScheduActivity::class.java),0) }

        recyclerYarnIn
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode== Activity.RESULT_OK){
            val item = data?.getParcelableExtra("schedu")as Itemm
            schedu = item
            tvScheduNo.text = "排班号："+item?.schedNo
        }
    }
}
